﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using Csla;
using Kiosk.Library;
using System.Collections.Generic;
using System.IO;

namespace Kiosk.WebManagement
{
    public partial class Presentation : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                pnlAdd.Visible = false;
                pnlVideoSelector.Visible = false;
                LoadFiles();
            }

            
            
        }

        private void LoadFiles()
        {
            List<string> temp = new List<string>(Directory.GetFiles(Server.MapPath("upload")));
            var files = from f in temp
                        where IsVideo(f)
                        select new
                        {
                            FileName = f.Substring(f.LastIndexOf("\\") + 1, f.Length - 1 - f.LastIndexOf("\\"))
                        };
            ddVideo.DataTextField = "FileName";
            ddVideo.DataValueField = "FileName";
            ddVideo.DataSource = files;
            ddVideo.DataBind();

        }

        private bool IsVideo(string fileName)
        { 
            bool isVideo = false;

            try
            {
                string ext = fileName.Split('.')[1].ToLower();
                string extensions = "avi,wmv,mpg,mpeg";
                var result = from s in extensions.Split(',')
                             where s.Contains(ext)
                             select s;
                isVideo = result.Count() > 0;
            }
            catch
            {
                isVideo = false;
            }
            return isVideo;
        }


        protected void PresentationsDatasource_SelectObject(object sender, Csla.Web.SelectObjectArgs e)
        {
            e.BusinessObject = PresentationReadOnlyList.GetAll();

        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            pnlAdd.Visible = true;
            Session["pres"] = Library.Presentation.NewPresentation();
            BindPresentation();
        }

        private void BindPresentation()
        {
            Library.Presentation pres = (Library.Presentation)Session["pres"];
            if (pres == null || pres.IsNew)
            {
                txtName.Text = "";
                ddStatus.SelectedIndex = -1;
                ddType.SelectedIndex = -1;
                ddType.Enabled = true;
            }
            else
            {
                txtName.Text = pres.Name;

                ddStatus.SelectedValue = pres.PresentationStatusID.ToString();
                ddType.SelectedValue = pres.PresentationTypeID.ToString();
                ddType.Enabled = false;
            }
        }

        protected void PresTypeDS_SelectObject(object sender, Csla.Web.SelectObjectArgs e)
        {
            e.BusinessObject = PresentationTypeReadOnlyList.GetAll();
        }
        protected void PresStatusDS_SelectObject(object sender, Csla.Web.SelectObjectArgs e)
        {
            e.BusinessObject = PresentationStatusReadOnlyList.GetAll();
        }

        protected void grdPresentations_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            Guid id = (Guid)e.Keys["PresentationID"];
            Kiosk.Library.Slide.DeleteAllByPresentationID(id);
            Kiosk.Library.Presentation.DeletePresentation(id);

        }

        protected void grdPresentations_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (grdPresentations.SelectedIndex >= 0)
            {
                Library.Presentation pres = Library.Presentation.GetPresentation((Guid)grdPresentations.SelectedValue);
                Session["pres"] = pres;
                if (pres.PresentationTypeName == "Slideshow")
                {
                    slideList.DataBind();
                    slideList.Visible = true;
                    pnlVideoSelector.Visible = false;
                }
                else if (pres.PresentationTypeName == "Video")
                {
                    SlideReadOnlyList slides = SlideReadOnlyList.GetSlidesByPresentationID(pres.PresentationID);
                    if (slides.Count == 1)
                    {
                        ddVideo.SelectedValue = slides[0].Location;
                    }
                    pnlVideoSelector.Visible = true;
                    slideList.Visible = false;
                }
                pnlAdd.Visible = false;
            }


        }

        #region Slide Events
        protected void SlidesDataSource_SelectObject(object sender, Csla.Web.SelectObjectArgs e)
        {
            if (grdPresentations.SelectedIndex >= 0)
            {
                SlideReadOnlyList slides = SlideReadOnlyList.GetSlidesByPresentationID((Guid)grdPresentations.SelectedValue);
                e.BusinessObject = slides;
            }
            else
            {
                e.BusinessObject = null;
            }
        }
 
        protected void slideList_ItemReorder(object sender, AjaxControlToolkit.ReorderListItemReorderEventArgs e)
        {
            Guid slideID = (Guid)slideList.DataKeys[e.Item.DataItemIndex];

            Slide.ReorderSlide(slideID, e.NewIndex);
        }

        protected void slideList_ItemDataBound(object sender, AjaxControlToolkit.ReorderListItemEventArgs e)
        {
            if (slideList.EditItemIndex == -1)
            {
                SlideInfo si = (SlideInfo)e.Item.DataItem;
                HyperLink h = (HyperLink)e.Item.FindControl("editLink");
                Button b = (Button)e.Item.FindControl("btnAdd");
                h.NavigateUrl = string.Format(h.NavigateUrl, si.SlideID);
                h.Attributes["onclick"] = string.Format(h.Attributes["onclick"], si.SlideID);
            }
        }

        protected void slideList_InsertCommand(object sender, AjaxControlToolkit.ReorderListCommandEventArgs e)
        {
            Library.Presentation pres = (Library.Presentation)Session["pres"];
            Slide s = Slide.NewSlide();
            s.PresentationID = ((Library.Presentation)Session["pres"]).PresentationID;
            s.Location = s.SlideID.ToString() + ".html";
            s.Order = SlideReadOnlyList.GetHighestOrderForPresentation(s.PresentationID) + 1;
            s.Title = ((TextBox)e.Item.FindControl("txtNewSlide")).Text;
            s.Save();
            slideList.DataBind();
            pnlVideoSelector.Visible = false;
            pnlAdd.Visible = true;
        }

        protected void deleteSlide_Command(object sender, CommandEventArgs e)
        {
            Slide.DeleteSlide(new Guid(e.CommandArgument.ToString()));
            slideList.DataBind();
        } 
        #endregion

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                Kiosk.Library.Presentation myPres = (Kiosk.Library.Presentation)Session["pres"];
                myPres.Name = txtName.Text;
                myPres.PresentationStatusID = new Guid(ddStatus.SelectedValue);
                myPres.PresentationTypeID = new Guid(ddType.SelectedValue);


                myPres.Save();
                pnlAdd.Visible = false;
                grdPresentations.DataBind();
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Session["note"] = null;
            pnlAdd.Visible = false;
            BindPresentation();
        }

        protected void grdPresentations_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "EditPres")
            {
                int index = int.Parse(e.CommandArgument.ToString());
                grdPresentations.SelectedIndex = index;
                Session["pres"] = Library.Presentation.GetPresentation((Guid)grdPresentations.DataKeys[index].Value);
                pnlAdd.Visible = true;
                slideList.Visible = false;
                pnlVideoSelector.Visible = false;
                BindPresentation();
            }
        }

        protected void grdPresentations_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow && e.Row.DataItem != null)
            {
                ImageButton editButton = (ImageButton)e.Row.Cells[1].Controls[0];
                
                //editButton.CommandArgument = ((Library.PresentationInfo)e.Row.DataItem).PresentationID.ToString();
                editButton.CommandArgument = e.Row.RowIndex.ToString();
            }
        }

        protected void btnChangeVideo_Click(object sender, EventArgs e)
        {
            Library.Presentation pres = (Library.Presentation)Session["pres"];
            SlideReadOnlyList slides = SlideReadOnlyList.GetSlidesByPresentationID(pres.PresentationID);
            Slide s = null;
            if (slides.Count == 0)
            {
                s = Slide.NewSlide();
            }
            else if (slides.Count == 1)
            {
                s = Slide.GetSlide(slides[0].SlideID);

            }
            else if (slides.Count > 1)
            {
                throw new Exception("Cannot have more than one video slide");
            }

            s.PresentationID = pres.PresentationID;
            s.Order = 0;
            s.Location = ddVideo.SelectedItem.Text;
            s.Title = ddVideo.SelectedItem.Text;
            s.Save();

        }
    }
}
